package com.hyk.commonLib.common.utils;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.google.zxing.BinaryBitmap;
import com.google.zxing.ChecksumException;
import com.google.zxing.FormatException;
import com.google.zxing.NotFoundException;
import com.google.zxing.RGBLuminanceSource;
import com.google.zxing.Result;
import com.google.zxing.common.GlobalHistogramBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import com.hyk.commonLib.common.activity.BaseActivity;
import com.hyk.commonLib.common.entity.ReqPermissionResult;
import com.hyk.commonLib.common.exception.CustomException;
import com.hyk.commonLib.common.exception.PermissionDeniedException;
import com.hyk.commonLib.common.utils.rx.activityResult.ActivityResultCompat;
import com.hyk.commonLib.common.utils.rx.activityResult.RxActivityResult;
import com.king.zxing.CameraScan;
import com.king.zxing.CaptureActivity;
import com.king.zxing.util.CodeUtils;

import java.io.File;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableOnSubscribe;
import io.reactivex.rxjava3.core.ObservableSource;
import io.reactivex.rxjava3.functions.Function;
import io.reactivex.rxjava3.schedulers.Schedulers;
import top.zibin.luban.Luban;

/**
 * Created by 贺玉琨 on 2019/6/12.
 */
public class QrCodeUtils {
    public static Observable<String> startScanQr(BaseActivity<?> activity) {
        Intent intent = new Intent(activity, CaptureActivity.class);
        return activity.requestPermissions(Manifest.permission.CAMERA)
                .flatMap((Function<ReqPermissionResult, ObservableSource<ActivityResultCompat>>) reqPermissionResult -> {
                    if (reqPermissionResult.isDeniedForever()) {
                        return Observable.error(new PermissionDeniedException());
                    }
                    return RxActivityResult.get(activity)
                            .start(intent)
                            .toObservable();
                })
                .flatMap((Function<ActivityResultCompat, ObservableSource<String>>) result -> {
                    if (result.isOk()) {
                        if (result.getData() != null) {
                            String content = result.getData().getStringExtra(CameraScan.SCAN_RESULT);
                            return Observable.just(content);
                        }
                    }
                    return Observable.empty();
                });
    }

    public static Observable<Result> decodeQr(Bitmap srcBitmap) {
        return Observable.create((ObservableOnSubscribe<Result>) emitter -> {
            if (srcBitmap != null) {
                File cacheFile = Luban.with(AppUtils.getAppContext())
                        .load(ImageUtils.saveBitmapToCache(srcBitmap))
                        .ignoreBy(200)
                        .setFocusAlpha(true)
                        .setTargetDir(AppUtils.getAppContext().getCacheDir().getAbsolutePath())
                        .get()
                        .get(0);
                Bitmap bitmap = BitmapFactory.decodeFile(cacheFile.getAbsolutePath());
                int width = bitmap.getWidth();
                int height = bitmap.getHeight();
                int[] pixels = new int[width * height];
                bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
                // 新建一个RGBLuminanceSource对象
                RGBLuminanceSource source = new RGBLuminanceSource(width, height, pixels);
                // 将图片转换成二进制图片
                BinaryBitmap binaryBitmap = new BinaryBitmap(new GlobalHistogramBinarizer(source));
                QRCodeReader reader = new QRCodeReader();// 初始化解析对象
                try {
                    emitter.onNext(reader.decode(binaryBitmap));
                } catch (NotFoundException | FormatException | ChecksumException e) {
                    e.printStackTrace();
                    emitter.onError(new CustomException("解析异常"));
                }
            } else {
                emitter.onError(new CustomException("图片不能为空"));
            }
        }).subscribeOn(Schedulers.computation()).observeOn(AndroidSchedulers.mainThread());
    }

    public static Bitmap createQrCode(String content) {
        return createQrCode(content, 400, null);
    }

    public static Bitmap createQrCode(String content, int height) {
        return createQrCode(content, height, null);
    }

    public static Bitmap createQrCode(String content, Bitmap logo) {
        return createQrCode(content, 400, logo);
    }

    public static Bitmap createQrCode(String content, int height, Bitmap logo) {
        return CodeUtils.createQRCode(content, height, logo);
    }
}
